
package net.sshiffon;

import com.jcraft.jsch.HostKey;
import com.jcraft.jsch.HostKeyRepository;
import com.jcraft.jsch.JSch;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.log4j.Logger;

/**
 *
 * @author amir
 */
public class KeyManager {
  private static Logger logger = Logger.getLogger(KeyManager.class);

  public static void saveKeys(JSch jsch, String knownHostsFile)
  {
                HostKeyRepository hkr = jsch.getHostKeyRepository();

          HostKey[] hks= hkr.getHostKey();
          if(hks!=null)
          {
            FileWriter f = null;
            try {
                logger.debug("host keys in " + hkr.getKnownHostsRepositoryID());
                f = new FileWriter(knownHostsFile);
                for (HostKey hk : hks) {
                    f.append(hk.getHost() + " " + hk.getType() + " " + hk.getKey() + "\n");
                    logger.trace(hk.getHost() + " " + hk.getType() + " " + hk.getKey() + " " + hk.getFingerPrint(jsch));
                }
                f.close();
            } catch (IOException ex) {
                logger.error("error writing hosts file", ex);
            } catch(Exception ex) {
                logger.error("error writing hosts file", ex);
            } finally {
                try {
                    f.close();
                } catch (IOException ex) {
                    logger.error("error closing hosts file", ex);
                }
            }


          }

  }
}
